<!DOCTYPE html>
<html>
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>传智健康</title>
    <meta name="description" content="传智健康">
    <meta name="keywords" content="传智健康">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <!-- 引入组件库 -->
    <script src="../js/vue.js"></script>
    <script src="../plugins/elementui/index.js"></script>
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <script src="../js/axios-0.18.0.js"></script>
    <style type="text/css">
        #container {
            height: 450px;
            width: 100%;
        }

        #l-map {
            height: 400px;
            width: 100%;
        }

        .tangram-suggestion-main {
            z-index: 999999;
        }

        #r-result {
            width: 100%;
        }

    </style>
    <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=3.0&ak=cxWPjLSLkP2NwvjMjAfBjYVG4OReUXVc"></script>
</head>
<body class="hold-transition">
<div id="app">
    <div class="content-header">
        <h1>地址管理</h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>工作台</el-breadcrumb-item>
            <el-breadcrumb-item>地址管理</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="分布图" name="first">
            <el-main>
                <div id="container"></div>
            </el-main>
        </el-tab-pane>
        <el-tab-pane label="详情信息" name="second">
            <div class="app-container">
                <div class="box">
                    <div class="filter-container">
                        <el-input placeholder="公司地址" v-model="pagination.queryString" style="width: 200px;"
                                  class="filter-item"></el-input>
                        <el-button @click="_findPage()" class="dalfBut">查询</el-button>
                        <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
                    </div>
                    <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                        <el-table-column type="index" align="center" label="序号"></el-table-column>
                        <el-table-column prop="address" label="公司地址" align="center"></el-table-column>
                        <el-table-column prop="longitude" label="所在经度" align="center"></el-table-column>
                        <el-table-column prop="latitude" label="所在纬度" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-container">
                        <el-pagination
                                class="pagiantion"
                                @current-change="handleCurrentChange"
                                :current-page="pagination.currentPage"
                                :page-size="pagination.pageSize"
                                layout="total, prev, pager, next, jumper"
                                :total="pagination.total">
                        </el-pagination>
                    </div>

                    <!-- 新增标签弹层 -->
                    <div class="add-form">
                        <el-dialog title="新增地址" :visible.sync="dialogFormVisible">

                            <div id="r-result">
                                <el-input id="suggestId"
                                          style="width: 200px;height: 34px;" class="filter-item"
                                          v-model="formData.address">
                                </el-input>
                                <el-button type="primary" class="butT" @click="handleAdd(formData.address)">确定添加
                                </el-button>
                            </div>
                            <div slot="footer">
                                <div id="searchResultPanel" class="panel"
                                     style="border:1px solid #6f9ec0;width:150px; display:none;"></div>
                                <div id="l-map"></div>
                            </div>

                        </el-dialog>

                    </div>
                </div>
            </div>
        </el-tab-pane>
    </el-tabs>
</div>

</body>
<!-- 引入样式 -->
<link rel="stylesheet" href="../plugins/elementui/index.css">
<link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="../css/style.css">
<script>

    var vue = new Vue({
        el: '#app',
        data: {
            activeName: 'first',

            pagination: {//分页相关模型数据
                currentPage: 1,//当前页码
                pageSize: 10,//每页显示的记录数
                total: 0,//总记录数
                queryString: null//查询条件
            },
            dataList: [],//当前页要展示的分页列表数据
            formData: {
                address: null,
                longitude: '',
                latitude: '',
            },//表单数据
            pp: null,
            dialogFormVisible: false,//增加表单是否可见
            rules: {//校验规则
                code: [{required: true, message: '项目编码为必填项', trigger: 'blur'}],
                name: [{required: true, message: '项目名称为必填项', trigger: 'blur'}]
            }
        },
        //钩子函数，VUE对象初始化完成后自动执行
        created() {
            this.findPage();
            //this.createdSmallMap();

        },
        mounted() {
            var map = new BMap.Map("container");
            map.enableScrollWheelZoom(true);
            var index = 0;
            var myGeo = new BMap.Geocoder();
            axios.post("/address/findAll.do").then((response) => {
                if (response.data.flag) {
                    var list = response.data.data;
                    var adds = [];
                    for (var i = 0; i < list.length; i++) {
                        adds.push(new BMap.Point(list[i].longitude, list[i].latitude));
                    }
                    for (var j = 0; j < adds.length; j++) {
                        map.centerAndZoom(adds[0], 13);
                        var marker = new BMap.Marker(adds[j]);
                        map.addOverlay(marker);
                        marker.setLabel(new BMap.Label(list[j].address, {offset: new BMap.Size(20, -10)}));

                    }
                }
            })
        },
        methods: {
            showMessage(r) {
                if (r == 'ERROR:Request failed with status code 403') {
                    this.$message.error("您没有足够的权限操作！");
                } else {
                    this.$message.error("未知错误！");
                    return;
                }
            },
            //添加
            handleAdd(address) {
                //检验表单输入是否合法

                var map = new BMap.Map("l-map");
                var localSearch = new BMap.LocalSearch(map);
                localSearch.enableAutoViewport(); //允许自动调节窗体大小
                var keyword = document.getElementById("suggestId").value;
                var num = 1;
                localSearch.setSearchCompleteCallback(function (searchResult) {
                    var poi = searchResult.getPoi(0);
                    var longitude = poi.point.lng;
                    var latitude = poi.point.lat;
                    if (num === 1) {
                        num++;
                        //1.创建核心对象
                        var xmlhttp;
                        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                            xmlhttp = new XMLHttpRequest();
                        } else {// code for IE6, IE5
                            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                        }

                        //2. 建立连接
                        xmlhttp.open("GET", "/address/add.do?longitude=" + longitude + "&latitude=" + latitude + "&address=" + address, true);

                        //3.发送请求
                        xmlhttp.send();

                        //4.接受并处理来自服务器的响应结果
                        //当xmlhttp对象的就绪状态改变时，触发事件onreadystatechange。
                      /*  xmlhttp.onreadystatechange = function () {
                            //判断readyState就绪状态是否为4，判断status响应状态码是否为200
                            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                                //获取服务器的响应结果
                                var responseText = xmlhttp.responseText;
                            }
                        }*/
                    }
                    //map.centerAndZoom(poi.point, 13);
                });
                localSearch.search(keyword);
                this.formData = {};
                this.dialogFormVisible = false;
                this._findPage();
            },
            _findPage() {
                this.pagination.currentPage = 1;
                this.findPage()
            },
            //分页查询
            findPage() {
                var param = {
                    currentPage: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    queryString: this.pagination.queryString
                };
                axios.post("/address/pageQuery.do", param).then((response) => {
                    this.pagination.total = response.data.total;
                    this.dataList = response.data.rows;
                }).catch((r) => {
                    this.showMessage(r);
                })
            },
            // 重置表单
            resetForm() {
                this.formData = {};
            },
            // 弹出添加窗口
            handleCreate() {
                this.resetForm();
                this.dialogFormVisible = true;
                this.createSmallMap();

            },

            //切换页码
            handleCurrentChange(currentPage) {
                this.pagination.currentPage = currentPage;
                this.findPage();
            },

            createSmallMap() {
                // 百度地图API功能
                function G(id) {
                    return document.getElementById(id);
                }

                var map = new BMap.Map("l-map");
                map.centerAndZoom("南京", 12);// 初始化地图,设置城市和地图级别。
                var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                    {
                        "input": "suggestId"
                        , "location": map
                    });
                ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
                    var str = "";
                    var _value = e.fromitem.value;
                    var value = "";
                    if (e.fromitem.index > -1) {
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                    value = "";
                    if (e.toitem.index > -1) {
                        _value = e.toitem.value;
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
                    G("searchResultPanel").innerHTML = str;
                });
                var myValue;
                ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
                    var _value = e.item.value;
                    myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                    G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
                    setPlace();
                });

                function setPlace() {
                    map.clearOverlays();    //清除地图上所有覆盖物
                    function myFun() {
                        this.pp = local.getResults().getPoi(0).point;//获取第一个智能搜索的结果
                        map.centerAndZoom(pp, 18);
                        map.addOverlay(new BMap.Marker(pp));   //添加标注

                    }

                    var local = new BMap.LocalSearch(map, { //智能搜索
                        onSearchComplete: myFun
                    },);
                    local.search(myValue);
                }


            },
            // 删除
            handleDelete(row) {
                this.$confirm('您确认删除吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.get("/address/del.do?id=" + row.id).then((response) => {
                        if (response.data.flag) {
                            this.$message({
                                type: 'success',
                                message: response.data.message
                            });
                            this.findPage();
                        } else {
                            this.$message.error(response.data.message);
                        }
                    }).catch((r) => {
                        this.showMessage(r);
                    });

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        }
    });
</script>
</html>